// This File is part of the "nyaqt" Project
// 
// Copyright  2009 sometmes@gmail.com
// All rights reserved
// 
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;
using System.Diagnostics;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace Notify2
{
    public partial class OptionsForm : Form
    {
        [DllImport("user32")]
        public static extern UInt32 SendMessage(IntPtr hWnd, UInt32 msg, UInt32 wParam, UInt32 lParam);
        internal const int BCM_FIRST = 0x1600; //Normal button
        internal const int BCM_SETSHIELD = (BCM_FIRST + 0x000C); //Elevated button

        public OptionsForm()
        {
            InitializeComponent();

            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            bool admin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            //admin = false;//DEBUG
            adminButton.Visible = !admin;
            registerRightClickCheckBox.Enabled = admin;
            string path = null;
            RegistryKey key;
            const string APPPATHS = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";

            ChooseBrowser b = new ChooseBrowser();
            b.Id = "default";
            b.Name = "(System Default)";
            b.IsDefault = true;
            b.SupportsProfiles = false;
            browserComboBox.Items.Add(b);

            b = new ChooseBrowser();
            b.Id = "chrome";
            b.Name = "Google Chrome";
            b.IsDefault = false;
            path = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "Google\\Chrome\\Application\\chrome.exe");
            if (!File.Exists(path))
            {
                path = "";
                using (key = Registry.LocalMachine.OpenSubKey(APPPATHS + "chrome.exe"))
                {
                    if (key != null)
                        path = key.GetValue("") as string;
                }
            }
            b.ApplicationPath = path;
            b.SupportsProfiles = true;
            b.ProfileOption = @"-user-data-dir=""..\User Data\{0}""";
            if (File.Exists(path))
                browserComboBox.Items.Add(b);

            b = new ChooseBrowser();
            b.Id = "IE";
            b.Name = "Microsoft Internet Explorer";
            b.IsDefault = false;
            using (key = Registry.LocalMachine.OpenSubKey(APPPATHS + "iexplore.exe"))
            {
                if (key != null)
                    path = key.GetValue("") as string;
            }
            b.ApplicationPath = path;
            b.SupportsProfiles = false;
            if (File.Exists(path))
                browserComboBox.Items.Add(b);

            b = new ChooseBrowser();
            b.Id = "firefox";
            b.Name = "Mozilla Firefox";
            b.IsDefault = false;
            using (key = Registry.LocalMachine.OpenSubKey(APPPATHS + "firefox.exe"))
            {
                if (key != null)
                    path = key.GetValue("") as string;
            }
            b.ApplicationPath = path;
            b.SupportsProfiles = true;
            b.ProfileOption = "-P {0}";
            if (File.Exists(path))
                browserComboBox.Items.Add(b);


            if (Properties.Settings.Default.v != "2")
            {
                Properties.Settings.Default.Login = "";
                Properties.Settings.Default.DecodedPwd = "";
                Properties.Settings.Default.v = "2";
            }
            loginTextBox.Text = Properties.Settings.Default.Login;
            pwdTextBox.Text = Properties.Settings.Default.DecodedPwd;

            saveAuthCheckbox.Checked = Properties.Settings.Default.SaveAuth;
            string browserid = Properties.Settings.Default.WebBrowser;
            browserComboBox.SelectedIndex = 0;
            foreach (ChooseBrowser b2 in browserComboBox.Items)
                if (b2.Id == browserid)
                    browserComboBox.SelectedItem = b2;

            ChooseBrowser b3 = browserComboBox.SelectedItem as ChooseBrowser;
            if (b3.SupportsProfiles)
                profileTextBox.Enabled = true;
            else
                profileTextBox.Enabled = false;

            profileTextBox.Text = Properties.Settings.Default.Profile;

            using (key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"))
            {
                autoStartCheckbox.Checked = (key.GetValue("GmailNotifier2-" + Properties.Settings.Default.Color, "") as string != "");
            }

            defaultImageSizeComboBox.Items.Clear();
            defaultImageSizeComboBox.Items.Add(Enums.ImageSizeOption640);
            defaultImageSizeComboBox.Items.Add(Enums.ImageSizeOption800);
            defaultImageSizeComboBox.Items.Add(Enums.ImageSizeOption1024);
            defaultImageSizeComboBox.Items.Add(Enums.ImageSizeOptionKeepOriginal);

            string defaultImageSize = Properties.Settings.Default.DefaultImageSize;
            foreach (ImageSizeOption option2 in defaultImageSizeComboBox.Items)
                if (option2.Id == defaultImageSize)
                    defaultImageSizeComboBox.SelectedItem = option2;

            string keyname = "Send To Gmail - " + Capitalize(Properties.Settings.Default.Color);
            using (key = Registry.ClassesRoot.OpenSubKey(@"*\shell"))
            {
                if (key != null)
                {
                    using (RegistryKey key2 = key.OpenSubKey(keyname))
                    {
                        if (key2 != null)
                        {
                            using (RegistryKey key3 = key2.OpenSubKey("Command"))
                            {
                                if (key3 != null)
                                {
                                    registerRightClickCheckBox.Checked = (key3.GetValue("", "") as string != "");
                                }
                            }
                        }
                    }
                }
            }
        }

        private void OptionsForms_Shown(object sender, EventArgs e)
        {
            SendMessage(adminButton.Handle, BCM_SETSHIELD, 0, 1);

            if (loginTextBox.Text != "" && pwdTextBox.Text == "")
                pwdTextBox.Focus();
            else if (loginTextBox.Text == "")
                loginTextBox.Focus();
        }

        private void OptionsForms_Load(object sender, EventArgs e)
        {
            this.Icon = Properties.Resources.ResourceManager.GetObject(Properties.Settings.Default.Color + "1") as Icon;
        }

        private void OptionsForms_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void OptionsForms_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            Save();
            Program.Startup = false;

            this.Hide();
        }

        string Capitalize(string text)
        {
            string colorCapitalized = text;
            colorCapitalized = colorCapitalized.Substring(0, 1).ToUpper() + colorCapitalized.Substring(1);
            return colorCapitalized;
        }

        private void Save()
        {
            Properties.Settings.Default.Login = loginTextBox.Text.Trim();
            if (saveAuthCheckbox.Checked)
            {
                Properties.Settings.Default.DecodedPwd = pwdTextBox.Text.Trim();
            }
            else
            {
                Properties.Settings.Default.Pwd = "";
            }
            Properties.Settings.Default.SaveAuth = saveAuthCheckbox.Checked;
            Properties.Settings.Default.WebBrowser = (browserComboBox.SelectedItem as ChooseBrowser).Id;
            Properties.Settings.Default.Profile = profileTextBox.Text;
            if (autoStartCheckbox.Checked)
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
                {
                    key.DeleteValue("GmailNotifier2",false); // old used value
                    key.SetValue("GmailNotifier2-" + Properties.Settings.Default.Color, Application.ExecutablePath + " /tray");
                }
            }

            Properties.Settings.Default.DefaultImageSize = (defaultImageSizeComboBox.SelectedItem as ImageSizeOption).Id;

            if (registerRightClickCheckBox.Enabled)
            {
                string keyname = "Send To Gmail - " + Capitalize(Properties.Settings.Default.Color);
                if (registerRightClickCheckBox.Checked)
                {
                    using (RegistryKey key0 = Registry.ClassesRoot.OpenSubKey(@"*", true))
                    {
                        RegistryKey key1;
                        using (key1 = Registry.ClassesRoot.OpenSubKey(@"*\shell", true))
                        {
                            if (key1 == null)
                                key1 = key0.CreateSubKey("shell");

                            // Old menu key
                            if (Array.IndexOf<string>(key1.GetSubKeyNames(), "SendToGmail") >= 0)
                                key1.DeleteSubKeyTree("SendToGmail");

                            RegistryKey key2;
                            using (key2 = key1.OpenSubKey(keyname, true))
                            {
                                if (key2 == null)
                                    key2 = key1.CreateSubKey(keyname);

                                RegistryKey key3;
                                using (key3 = key2.OpenSubKey("Command", true))
                                {
                                    if (key3 == null)
                                        key3 = key2.CreateSubKey("Command");
                                    key3.SetValue("", Application.ExecutablePath + " /send \"%1\"");
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(@"*\shell", true))
                    {
                        if (Array.IndexOf<string>(key.GetSubKeyNames(), keyname) >= 0)
                            key.DeleteSubKeyTree(keyname);
                    }
                }
            }

            Properties.Settings.Default.Save();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            if (Program.StayInTray)
            {
                if (Program.Startup)
                    Application.Exit();
                else
                    this.Hide();
            }
            else
                Application.Exit();
        }

        private void adminButton_Click(object sender, EventArgs e)
        {
            Save(); 
            
            ProcessStartInfo processStartInfo = new ProcessStartInfo(Application.ExecutablePath);
            processStartInfo.Verb = "runas";
            processStartInfo.UseShellExecute = true;
            processStartInfo.ErrorDialog = true;
            processStartInfo.ErrorDialogParentHandle = this.Handle;
            processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
            processStartInfo.Arguments = Process.GetCurrentProcess().StartInfo.Arguments;
            Process.Start(processStartInfo);
            Application.Exit();
        }

        private void profileTextBox_Validated(object sender, EventArgs e)
        {
            if (profileTextBox.Text.Trim() == "")
                profileTextBox.Text = "<Default>";
        }

        private void browserComboBox_Validated(object sender, EventArgs e)
        {

        }

        private void browserComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChooseBrowser browser = browserComboBox.SelectedItem as ChooseBrowser;
            if (browser.SupportsProfiles)
                profileTextBox.Enabled = true;
            else
                profileTextBox.Enabled = false;
        }
    }
}
















